using SqlSugar;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.Extensions.FileProviders;

var builder = WebApplication.CreateBuilder(args);
IConfiguration _config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSession();
builder.Services.AddMemoryCache();
builder.Services.AddMvc(options =>
{
    options.EnableEndpointRouting = false;
    options.Filters.Add(typeof(ApiData.Web.Filters.AuthFilter));
}).AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
builder.Services.AddScoped(options =>
{
    return new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = _config.GetConnectionString("SugarConnectString"),
        DbType = DbType.MySql,
        IsAutoCloseConnection = true
    }
    );
});
string corsName = "AllowCors";
builder.Services.AddCors(options =>
{
    options.AddPolicy(corsName, policy =>
    {
        policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
    });
});

var app = builder.Build();
app.UseSession(new SessionOptions()
{
    Cookie = new CookieBuilder()
    {
        Name = "APIDATA-NETCORE"
    }
});
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseCors(corsName);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "upload")),
    RequestPath = "/upload"
});
app.UseRouting();
app.UseAuthorization();
app.UseSession(new SessionOptions()
{
    Cookie = new CookieBuilder()
    {
        Name = "APIDATA-NETCORE-IDENTITY"
    }
});
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}"
        );
});
app.Run();